package com.thread;

/**
 * 原生的notify,wait方法
 * 实现两个线程交替打印奇偶数
 * @author yaojinshan
 *
 */
public class SwapPrintNum {
	static int currentNum = 0;
	static int maxNum = 100;
	void increate(){
		currentNum++;
	}
	
	int getCurrentNum(){
		return currentNum;
	}
	
	public static void main(String[] args) {
		final  SwapPrintNum sp = new SwapPrintNum();
		Thread t1 = new Thread(new Runnable() {
			public void run() {
				while(sp.getCurrentNum() < maxNum){
					synchronized (sp) {
						//System.out.println("------执行notify()之后，该线程可以重复获取到锁，所以要加下边的else判断，让该线程释放锁，以便其他线程获取到锁------");
						if(sp.getCurrentNum() % 2 == 0){
							System.out.println(Thread.currentThread().getName() + "输出：" +  sp.getCurrentNum());
							sp.increate();
							//notify 并不立即释放锁  继续持有对象的锁  
							sp.notify();
						}else{
							//该线程  满足if条件 执行完毕之后 ，由于值发生改变 ，导致if条件不满足，所以走else块,主动调用wait()方法 释放一下锁
							try {
								sp.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		},"-------");
		Thread t2 = new Thread(new Runnable() {
			public void run() {
				while(sp.getCurrentNum() < maxNum){
					synchronized (sp) {
						if(sp.getCurrentNum() % 2 != 0){
							System.out.println(Thread.currentThread().getName() + "输出：" +  sp.getCurrentNum());
							sp.increate();
							sp.notify();
						}else{
							try {
								sp.wait();
							} catch (InterruptedException e) {
								e.printStackTrace();
							}
						}
					}
				}
			}
		},"---");
		t1.start();
		t2.start();
	}

}
